package me.dwliu.lab.demo.webflux;

import lombok.extern.slf4j.Slf4j;
import me.dwliu.lab.demo.webflux.exception.BusinessException;
import me.dwliu.lab.demo.webflux.exception.ServiceExceptionEnum;
import me.dwliu.lab.demo.webflux.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.server.ServerWebInputException;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 处理 ServiceException 异常
     */
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Result serviceExceptionHandler(BusinessException ex) {
        log.debug("[serviceExceptionHandler]", ex);
        // 包装 CommonResult 结果
        return Result.error(ex.getCode(), ex.getMessage());
    }

    /**
     * 处理 ServerWebInputException 异常
     * <p>
     * WebFlux 参数不正确
     */
    @ResponseBody
    @ExceptionHandler(value = ServerWebInputException.class)
    public Result serverWebInputExceptionHandler(ServerWebInputException ex) {
        log.debug("[ServerWebInputExceptionHandler]", ex);
        // 包装 CommonResult 结果
        return Result.error(ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getCode(),
                ServiceExceptionEnum.MISSING_REQUEST_PARAM_ERROR.getMessage());
    }

    /**
     * 处理其它 Exception 异常
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception e) {
        // 记录异常日志
        log.error("[exceptionHandler]", e);
        // 返回 ERROR CommonResult
        return Result.error(ServiceExceptionEnum.SYS_ERROR.getCode(),
                ServiceExceptionEnum.SYS_ERROR.getMessage());
    }

}
